import store from '@/store'
import config from '@/config'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import { toast, showConfirm, tansParams } from '@/utils/common'

let timeout = 10000
const baseUrl = config.baseUrl

const request = config => {
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false
  config.header = config.header || {}
  if (getToken() && !isToken) {
    config.header['Authorization'] = 'Bearer ' + getToken()
  }
  // get请求映射params参数
  if (config.params) {
    let url = config.url + '?' + tansParams(config.params)
    url = url.slice(0, -1)
    config.url = url
  }
  return new Promise((resolve, reject) => {
    uni.request({
        method: config.method || 'get',
        timeout: config.timeout ||  timeout,
        url: config.baseUrl || baseUrl + config.url,
        data: config.data,
        header: config.header,
        dataType: 'json'
      }).then(response => {
        let [error, res] = response
        if (error) {
          toast('后端接口连接异常')
          reject('后端接口连接异常')
          return
        }
        const code = res.data.code || 200
        const msg = errorCode[code] || res.data.msg || errorCode['default']
        
        // 处理token过期情况
        if (code === 401) {
          // 如果已经在处理token过期，直接拒绝请求
          if (store.state.user.isHandlingTokenExpired) {
            reject('token过期处理中')
            return
          }
          
          store.dispatch('SetIsHandlingTokenExpired', true)
          
          // 统一提示并处理
          uni.showToast({
            title: '登录已过期，请重新登录',
            icon: 'none',
            duration: 2000,
            complete: () => {
              // 清除登录信息
              store.dispatch('LogOut').then(() => {
                // 延迟跳转，确保用户看到提示
                // setTimeout(() => {
                  // 记录当前页面路径
                  const pages = getCurrentPages()
                  const currentPage = pages[pages.length - 1]
                  if (currentPage && currentPage.route && !checkWhite('/' + currentPage.route)) {
                    store.dispatch('SetRedirectPage', '/' + currentPage.route)
                  }
                  store.dispatch('SetIsHandlingTokenExpired', false)
                  uni.reLaunch({ 
                    url: '/pages/login',
                  })
                // }, 1500)
              })
            }
          })
          reject('登录已过期')
          return
        } else if (code === 500) {
          toast(msg)
          reject('500')
        } else if (code !== 200) {
          toast(msg)
          reject(code)
        }
        resolve(res.data)
      })
      .catch(error => {
        let { message } = error
        if (message === 'Network Error') {
          message = '后端接口连接异常'
        } else if (message.includes('timeout')) {
          message = '系统接口请求超时'
        } else if (message.includes('Request failed with status code')) {
          message = '系统接口' + message.substr(message.length - 3) + '异常'
        }
        toast(message)
        reject(error)
      })
  })
}

// 添加检查白名单方法
function checkWhite(url) {
  const whiteList = [
    '/pages/login',
    '/pages/register',
    '/pages/common/webview/index',
    '/pages/loginForPhone',
    '/pages/accountLogin'
  ]
  const path = url.split('?')[0]
  return whiteList.indexOf(path) !== -1
}

export default request
